/* eslint-disable jsx-a11y/anchor-is-valid */
import React, { useState } from "react";
import {useQuery} from "@tanstack/react-query";
import axios from 'axios'


export default function Stale_CacheTime() {
  const [state, setState] = useState(0);
  const { isLoading, error, data, isFetching, isStale, fetchStatus } = useQuery({
    queryKey: ["repoData", state],
    queryFn: () => {
      return axios
        .get("https://jsonplaceholder.typicode.com/todos/1")
        .then((res) => res.data);
    },
    // 虽然 cacheTime 为 0，但是如果被 observer 引用，还是不会删除
    cacheTime: 0,
    // queryKey 变化后，query 更新了，内部也会被当做过期的，因为没有请求过
    staleTime: 100000,
    refetchOnWindowFocus: false
  });
  // console.log("isStale: ", isStale);
  // console.log("isFetching: ", isFetching, isStale);
  // console.log("isLoading: ", isLoading);

  if (isLoading) return "Loading...";

  if (error) return "An error has occurred: " + error.message;

  return (
    <div>
      <h1 onClick={() => setState(state + 1)}>{data.title}</h1>
      <hr/>
    </div>
  );
}


export const OtherStale_CacheTime = () => {
  const [state, setState] = useState(0);
  const { isLoading, error, data, isFetching } = useQuery({
    queryKey: ["repoData"],
    queryFn: () => {
      console.log('start fetching')
      return axios
        .get("https://jsonplaceholder.typicode.com/todos/2")
        .then((res) => res.data);
    },
    // cacheTime: 0,
    staleTime: 1000,
    refetchOnWindowFocus: false
  });


  if (isLoading) return "Other Loading...";

  if (error) return "An error has occurred: " + error.message;

  return (
    <div>
      <h1 onClick={() => setState(state + 1)}>Other {data.title}</h1>
    </div>
  );
}
